package exercise;

/**
 * leetcode简单题：一个字符串数组的最长公共前缀
 */

public class Solution {
    public static void main(String[] args) {
        String[] strs = new String[3];
        strs[0] = "flower";
        strs[1] = "flow";
        strs[2] = "flo";
        System.out.println(longestCommonPrefix(strs));
    }

    public static String longestCommonPrefix(String[] strs) {
        StringBuffer stringBuffer = new StringBuffer();
        int minLen = 1000000000;
        for(int i = 0; i < strs.length; i++) {
            int len = strs[i].length();
            if(minLen > len) {
                minLen = len;
            }
            if(strs[i] == null || len == 0) {
                return "";
            }
        }
        for(int i = 0; i < minLen; i++) {
            char ch = strs[0].charAt(i);
            int j = 0;
            for(j = 1; j < strs.length; j++) {
                if(ch != strs[j].charAt(i)) {
                    break;
                }
            }
            if(j >= strs.length) {
                stringBuffer.append(ch);
            }else {
                break;
            }
        }
        if(stringBuffer.length() == 0) {
            return "";
        }else {
            return stringBuffer.toString();
        }
    }
}